package at.fhooe.mcm.logic.sensors.entities;

import java.io.Serializable;

import at.fhooe.mcm.logic.core.Core;
import at.fhooe.mcm.logic.event.EventManager;
import at.fhooe.mcm.logic.logging.ConsoleLoggingService;
import at.fhooe.mcm.logic.sensors.Sensor;
import at.fhooe.mcm.logic.sensors.events.SensorUpdatedEvent;

public class AirpressureSensor extends Sensor implements Serializable
{
	/**
	 * 
	 */
	private static final long	serialVersionUID	= 3450047623212330998L;
	private double				m_currentPressure;
	private boolean				m_isPushingData;

	public AirpressureSensor(Core _core, String _id, String _name, boolean _isPublic, boolean _isPull, int _updatePeriod)
	{
		super(_core, _id, _name, _isPublic, _isPull, _updatePeriod);
	}

	public static final String	TYPE	= "AirPressureSensor";

	@Override
	public String getType()
	{
		return TYPE;
	}

	@Override
	protected void setUp()
	{
		if (!m_isPull && !m_isPushingData)
		{
			m_isPushingData = true;
			m_thread.start();
		}
	}

	@Override
	protected void tearDown()
	{
		if (!m_isPull)
		{
			m_isPushingData = false;
		}
	}

	@Override
	public void update()
	{
		if (m_isPull)
		{
			m_currentPressure = Math.random() * 2 * 1000;
			ConsoleLoggingService.getInstance(m_core).logInfo("AIRPRESSURE SENSOR", "Pull " + String.valueOf(m_currentPressure));

			SensorUpdatedEvent event = new SensorUpdatedEvent(m_id, TYPE, m_name, m_currentPressure);
			EventManager.getInstance(m_core).enqueueEvent(event);
		}
	}

	@Override
	public void run()
	{
		try
		{
			while (m_isPushingData)
			{
				m_currentPressure = Math.random() * 2 * 1000;
				if (!m_isPull)
				{
					SensorUpdatedEvent event = new SensorUpdatedEvent(m_id, TYPE, m_name, m_currentPressure);
					EventManager.getInstance(m_core).enqueueEvent(event);

					ConsoleLoggingService.getInstance(m_core).logInfo("AIRPRESSURE SENSOR", "Push " + String.valueOf(m_currentPressure));
				}

				Thread.sleep(m_updatePeriod);
			}
		}
		catch (InterruptedException e)
		{
			ConsoleLoggingService.getInstance(m_core).logDebug("AIRPRESSURE SENSOR", e.getMessage());
		}
	}
}
